let $socket = new Socket({
	// url: 'ws://ws.18008888.com:1010/wss',
	url: 'wss://admin.zgranqi.com:1010',
	reconnectionTryNum: 20,
	autoEmitBuffer: true,
	heartRate: 30000,
	// heartRate: 10000,
	heartRateType: 'heart',
	// token: store.getters.token,
})
// 图表库实例化后储存的函数
var widget = null
// 进入页面 默认展示的产品
var index_market = 'GC'
// 进入页面 默认展示的产品周期
var index_activeCycle = '1'

function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]); return null;
}
var symbol = GetQueryString("symbol")

if (symbol && symbol != '[object Object]') {
	index_market = symbol
	document.title = symbol.toUpperCase()
}

console.log(symbol,'symbol')

if(!localStorage.getItem('lang')){
	localStorage.setItem('lang','zh');
}

// console.log(localStorage.getItem('lang'));


if (localStorage.getItem('lang') == 'hk') {
	document.getElementById('opening').innerText = "開盤";
	document.getElementById('volume').innerText = "成交量";
	document.getElementById('lowest').innerText = "最低";
	document.getElementById('highest').innerText = "最高";
	// document.getElementById('wan').innerText = "萬";
} else if (localStorage.getItem('lang') == 'kr') {
	document.getElementById('opening').innerText = "열리는";
	document.getElementById('volume').innerText = "용량";
	document.getElementById('lowest').innerText = "가장 낮은";
	document.getElementById('highest').innerText = "제일 높은";
	// document.getElementById('wan').innerText = "만";
} else if (localStorage.getItem('lang') == 'jp') {
	document.getElementById('opening').innerText = "オープニング";
	document.getElementById('volume').innerText = "音量";
	document.getElementById('lowest').innerText = "最低";
	document.getElementById('highest').innerText = "最高";
	// document.getElementById('wan').innerText = "万";
} else if (localStorage.getItem('lang') == 'en') {
	document.getElementById('opening').innerText = "opening";
	document.getElementById('volume').innerText = "volume";
	document.getElementById('lowest').innerText = "lowest";
	document.getElementById('highest').innerText = "highest";
	// document.getElementById('wan').innerText = "ten thousand";
} else if (localStorage.getItem('lang') == 'vn') {
	document.getElementById('opening').innerText = "khai mạc";
	document.getElementById('volume').innerText = "âm lượng";
	document.getElementById('lowest').innerText = "thấp nhất";
	document.getElementById('highest').innerText = "Cao nhất";
	// document.getElementById('wan').innerText = "Mười nghìn";
} else if (localStorage.getItem('lang') == 'lta') {
	document.getElementById('opening').innerText = "Early morning";
	document.getElementById('volume').innerText = "Volume";
	document.getElementById('lowest').innerText = "LOW";
	document.getElementById('highest').innerText = "HiG";
	// document.getElementById('wan').innerText = "Mười nghìn";
} else if (localStorage.getItem('lang') == 'es') {
	document.getElementById('opening').innerText = "Temprano en la mañana";
	document.getElementById('volume').innerText = "Volumen";
	document.getElementById('lowest').innerText = "BAJO";
	document.getElementById('highest').innerText = "Alto";
	// document.getElementById('wan').innerText = "Mười nghìn";
}

function revInfo(data) {
	if(!data || !data.close) {
		return
	}
	
	document.getElementById('close').innerText = data.close
	document.getElementById('cny').innerText = data.increase
	document.getElementById('change').innerText = (data.ratio > 0 ? '+' : '') + data.ratio + '%'
	document.getElementById('high').innerText = data.high
	document.getElementById('low').innerText = data.low
	document.getElementById('amount').innerText = data.amount
	// document.getElementById('amount').innerText = (data.amount / 10000)
	document.getElementById('open').innerText = data.open
	
	
	var color = ''
	if (data.ratio > 0) {
		color = "#1cad90"
	}
	if (data.ratio < 0) {
		color = "#ff6059"
	}
	document.getElementById('close').style.color = color
	document.getElementById('change').style.color = color
	document.getElementById('cny').style.color = color
}

function initOnReady() {
	
	if(index_market) {
		$socket.on('sub.futures.info@kline', revInfo, true, {"code": index_market})
	}
	
	const chart = new chartKlinex({
		id: 'tv_chart_container',
		socket: $socket,
		resolution: 1,
		intervals: ['Time', '1M', '5M', '15M', '30M', '1H', '1D', '1M'],
		symbol: index_market,
		name: '纽约黄金',
	})
	
	// 切换产品周期
	document.getElementById('interval').addEventListener('click', function (e) {
		if(e.target.nodeName !== 'SPAN') {
			return
		}
		
		chart.setChartType(e.target.dataset.value == '2' ? 3 : 1)
		chart.setResolution(e.target.dataset.value)
		
		// 1 为平均K线； 3 为面积图
		 // widget.chart().setChartType(e.target.dataset.value == '2' ? 3 : 1)
		// widget.chart().setResolution(e.target.dataset.value)
		// 这个函数不用看，我为了样式好看 写一个添加删除class
		// addClass(intervalDom, e.target)
		
		document.querySelectorAll('#interval .active')[0].classList.remove('active')
		e.target.classList.add('active')
	}, false)
}

window.addEventListener('DOMContentLoaded', initOnReady, false);


class chartKlinex
{
	constructor(options = {}) {
		this.chart = null
		this.options = options
		this.intervals = ['Time', '1M', '5M', '15M', '30M', '1H', '1D', '1M']
		this.socket = $socket
		this.period = null
		this.width = null
		this.height = null
		this.data = []
		this.historyData = null
		this.series = null
		this.smaSeries = null
		this.volumeSeries = null
		
		this.init()
		
		return this
	}
	
	/**
	 * @param {date} timestamp 需要转换的时间
	 * @param {String} format 需要转换的格式 如 Y-m-d H:i:s
	 */
	formatTime(timestamp, format) {
		if(('' + timestamp).length <= 10) {
			timestamp = timestamp * 1000
		}
		
		let _date = new Date(timestamp),
			Y = _date.getFullYear(),
			m = _date.getMonth() + 1,
			d = _date.getDate(),
			H = _date.getHours(),
			i = _date.getMinutes(),
			s = _date.getSeconds()

		m = m < 10 ? '0' + m : m
		d = d < 10 ? '0' + d : d
		H = H < 10 ? '0' + H : H
		i = i < 10 ? '0' + i : i
		s = s < 10 ? '0' + s : s

		return format.replace(/[YmdHis]/g, key=>{
			return {Y,m,d,H,i,s}[key]
		});
	}
	
	init() {
		let _this = this
		this.chart = LightweightCharts.createChart(this.options.id, {
			localization: {
				dateFormat: 'yyyy-MM-dd',
				timeFormatter: businessDayOrTimestamp => {
					return _this.formatTime(businessDayOrTimestamp, 'Y-m-d H:i')
					/*
					if (LightweightCharts.isBusinessDay(businessDayOrTimestamp)) {
						return 'Format for business day';
					}
					return 'Format for timestamp'
					*/
				},
			},
			rightPriceScale: {
				scaleMargins: {
					top: 0.1,
					bottom: 0.1,
				},
			},
			timeScale: {
				timeVisible: true,
				secondsVisible: false,
				tickMarkFormatter: (time, tickMarkType, locale) => {
					if(tickMarkType == 2) {
						return _this.formatTime(time, 'Y-m-d')
					}
					
					if(tickMarkType == 3) {
						return _this.formatTime(time, 'H:i')
					}
					
					return _this.formatTime(time, 'Y')
				}
			},
		})
		
		// this.setResolution(this.options.resolution || 1)
		
		this.container = document.querySelectorAll('#'+ this.options.id)[0]
		
		this.width = this.container.clientWidth
		this.height = this.container.clientHeight
		
		this.setPeriod(this.options.resolution)
		
		// 默认订阅
		this.subscribe()
		// this.period = this.getPeriod(this.options.resolution)
	}
	
	addSeriesAndData(data, options) {
		let type
		if(this.period == '1M') {
			type = 'area'
			options = {
				topColor: 'rgba(76, 175, 80, 0.56)',
				bottomColor: 'rgba(76, 175, 80, 0.04)',
				lineColor: 'rgba(76, 175, 80, 1)',
				lineWidth: 2,
				// title: this.options.name || this.options.symbol,
			}
			// 禁用缩放滚动
			this.chart.applyOptions({
			    handleScroll: false,
			    handleScale: false,
			})
		} else {
			type = 'candlestick'
			// 允许缩放滚动
			this.chart.applyOptions({
				handleScroll: true,
				handleScale: true,
			})
		}
		
		if (this.series && this.chart) {
			this.chart.removeSeries(this.series)
		}
		
		const seriesConstructor = `add${type.charAt(0).toUpperCase() + type.slice(1)}Series`
		this.series = this.chart[seriesConstructor](options);
		this.series.setData(data)
	}

	sub(event, data) {
		$socket.on('sub.futures.kline', this.revKline, true, data)
		// this.socket.sendMsg({event: event, data: data })
	}
	
	subscribe() {
		let nowDate = new Date().getTime()
		
		if(this.period == '1M') {
			
		} else if(this.period == '5M') {
			
		} else if(this.period == '15M') {
		} else if(this.period == '30M') {
		} else if(this.period == '1H') {
		} else if(this.period == '1D') {
		} else if(this.period == '1W') {
			/*
			this.chart.timeScale().setVisibleRange({
			    from: nowDate - 7 * 24 * 60 * 60 / 1000,
			    to: nowDate / 1000,
			})
			this.chart.timeScale().fitContent()*/
		}
		
		if(this.historyData) {
			if(this.historyData.period == this.period) {
				return false
			}
			
			this.unsubscribe(this.historyData.period)
			// this.sub('unsub.futures.kline', this.historyData, true)
		}
		
		this.historyData = {"code": this.options.symbol, period: this.period }
		
		// this.sub('sub.futures.kline', this.historyData, true)
		$socket.on(
			'sub.futures.kline@' + this.period,
			(res) => {
				this.revKline(res)
			},
			true, 
			this.historyData ,
		)
	}
	
	unsubscribe(period) {
		period = period || this.period
		$socket.on(
			'unsub.futures.kline@' + period,
			(res) => {
				this.revKline(res)
			},
			true,
			{"code": this.options.symbol, period: period },
		)
		// this.sub('unsub.futures.kline', {"code": this.options.symbol, period: period }, true)
	}
	
	setPeriod(resolution) {
		if(resolution == 1 || resolution == 2) {
			this.period = '1M'
			return '1M'
		}
		
		if(resolution == 5) {
			this.period = '5M'
			return '5M'
		}
		
		if(resolution == 15) {
			this.period = '15M'
			return '15M'
		}
		
		if(resolution == 30) {
			this.period = '30M'
			return '30M'
		}
		
		if(resolution == 60) {
			this.period = '1H'
			return '1H'
		}
		
		if(resolution == '1D') {
			this.period = '1D'
			return '1D'
		}
		
		if(resolution == '1W') {
			this.period = '1W'
			return '1W'
		}
	}
	
	setChartType(type) {
		// this.chart.applyOptions
	}
	
	setResolution(resolution) {
		this.setPeriod(resolution)
		
		this.subscribe()
		// this.sub('sub.futures.kline', {"code": this.options.symbol, period: this.period }, true)
	}

	getData() {
		return this.data
	}
	setData(data) {
		this.data = data
	}
	
	updateData(data) {
		this.data.push(data)
	}
	
	getLastItem() {
		if(this.data &&  this.data.length) {
			return this.data[this.data.length - 1] || null
		}
		return null
	}
	
	addVolumeSeries(isRemove) {
		if(!this.volumeSeries) {
			this.volumeSeries = this.chart.addHistogramSeries({
				// title: 'Volume',
				color: '#26a69a',
				priceFormat: {
					type: 'volume',
				},
				priceScaleId: '',
				scaleMargins: {
					top: 0.9,
					bottom: 0,
				},
			})
		}
		
		if(isRemove) {
			this.chart.removeSeries(this.volumeSeries)
			this.volumeSeries = null
			return 
		}
		
		let data = this.getData()
		if(data) {
			let volumeData = []
			data.forEach((i) => {
				volumeData.push({
					time: i.time,
					value: Number(i.volume) || 0,
					color: (i.ratio > 0 ? 'rgba(0, 150, 136, 0.8)' : 'rgba(255,82,82, 0.8)'),
				})
			})
			
			this.volumeSeries.setData(volumeData)
		}
	}

	
	calculateSMA(data, count) {
		var avg = function(data) {
			var sum = 0;
			for (var i = 0; i < data.length; i++) {
				sum += data[i].close
			}
			return sum / data.length
		}
		
		var result = []
		for (var i = count - 1, len = data.length; i < len; i++) {
			var val = avg(data.slice(i - count + 1, i))
			result.push({ time: data[i].time, value: val})
		}
		
		return result
	}
	
	createMA(isRemove) {
		
		if(!this.smaSeries) {
			this.smaSeries = this.chart.addLineSeries({
				color: 'rgba(4, 111, 232, 1)',
				lineWidth: 2,
			})	
		}
		
		if(isRemove) {
			this.chart.removeSeries(this.smaSeries)
			this.smaSeries = null
			return 
		}
		
		let smaData = this.calculateSMA(this.getData(), 10)
		
		this.smaSeries.setData(smaData)	
	}
	
	createToolTip() {
		let toolTip = document.querySelector('.three-line-legend')
		
		
		var toolTipMargin = 10
		var priceScaleWidth = 50
		
		if(!toolTip) {
			toolTip = document.createElement('div')
			toolTip.className = 'three-line-legend'
			this.container.appendChild(toolTip)
		}
		
		toolTip.style.display = 'flex';
		toolTip.style.left = 3 + 'px';
		toolTip.style.top = 3 + 'px';
		let _this = this
		
		function businessDayToString(time) {
			var d = new Date(time * 1000)
			return d.getFullYear() +'-'+ d.getMonth() +'-'+ d.getDay() +' '+ d.getHours() +':'+ d.getMinutes()
		}
		
		function getLegendText(priceValue) {
			let val = '∅';
			if (priceValue !== undefined) {
				val = (Math.round(priceValue * 100) / 100).toFixed(2)
			}
			
			return '<div>MA10 <span style="color:rgba(4, 111, 232, 1)">' + val + '</span></div>'
		}
		
		function setLastBarText() {
			let item = _this.getLastItem()
			if(!item) {
				return
			}
			
			let format = 'Y-m-d'
			if(_this.period == '1M') {
				format = 'H:i'
			}
			let dateStr = _this.formatTime(item.time, format)
			// let name = _this.options.name || _this.options.symbol
			let close = item.close || item.value
			toolTip.innerHTML =`
				<!--div style="font-size: 24px; margin: 4px 0px; color: #20262E">${ name }</div-->
				<div>${ dateStr }</div>
				<div style="font-size: 22px; margin: 4px 0px; color: #20262E">${ close }</div>
				${getLegendText(close)}
			`
		}
		
		setLastBarText()
		
		this.chart.subscribeCrosshairMove(function(param) {
			if (
				param === undefined ||
				param.time === undefined ||
				param.point.x < 0 ||
				param.point.x > _this.width ||
				param.point.y < 0 ||
				param.point.y > _this.height
			) {
				setLastBarText();   
			} else {
				let dateStr = ''
				if(typeof(param.time) == 'number') {
					let format = 'Y-m-d'
					if(_this.period == '1M') {
						format = 'H:i'
					}
					dateStr = _this.formatTime(param.time, format)
				} else {
					dateStr = param.time.year +' - '+ param.time.month + ' - ' + param.time.day
				}
				
				if(!_this.series) {
					return
				}
				
				let item = param.seriesPrices.get(_this.series)
				if(!item) {
					return
				}
				let close = item.close || item.value || item
				let name = _this.options.name || _this.options.symbol
				toolTip.innerHTML =	`
					<!--div style="font-size: 24px; margin: 4px 0px; color: #20262E"> ${name}</div-->
					<div>${ dateStr }</div>
					<div style="font-size: 22px; margin: 4px 0px; color: #20262E">${ close }</div>
					${getLegendText(close)}
				`
			}
		})
	}
	
	revKline(data) {
		if (!data) {
			return false
		}
		
		let _this = this
		
		if(data && Array.isArray(data)) {
			let list = []
			if(this.period == '1M') {
				data.forEach((i) => {
					list.push({
						time: i.time,
						date: i.date,
						ratio: i.ratio,
						increase: i.increase,
						value: Number(i.close),
						volume: Number(i.volume),
					})
				})
			
				_this.setData(list)
				_this.createMA()
				_this.addVolumeSeries(true)
				_this.chart.timeScale().fitContent()
			} else {
				data.forEach((i) => {
					list.push({
						// time: i.date,
						time: i.time,
						ratio: i.ratio,
						increase: i.increase,
						low: Number(i.low) || 0,
						open: Number(i.open) || 0,
						high: Number(i.high) || 0,
						close: Number(i.close) || 0,
						volume: Number(i.volume) || 0,
					})
				})
				
				_this.setData(list)
				_this.createMA()
				_this.addVolumeSeries()
				_this.chart.timeScale().resetTimeScale()
			}
			
			_this.createToolTip()
			_this.addSeriesAndData(list)
		} else {
			if (Object.prototype.toString.call(data) === '[object Object]' && data.hasOwnProperty('close')) {
				/*onTick({
					time: data.time * 1000,
					close: Number(data.close),
					// open: Number(data.open),
					// high: Number(data.high),
					// low: Number(data.low),
					volume: Number(data.volume)
				})*/
				let add = {
					// time: data.date,
					time: Number(data.time),
					// low: Number(data.low) || 0,
					// open: Number(data.open) || 0,
					// high: Number(data.high) || 0,
					// close: Number(data.close) || 0,
					value: Number(data.close) || 0,
					volume: Number(data.volume)
				}
				
				let lastItem = this.getLastItem()
				
				if(lastItem && lastItem.time > Number(add.time)) {
					// console.log(`Cannot update oldest data, last time=${ lastItem.time }, new time=${ data.time }`)
					return
				}
				
				this.updateData(add)
				this.series.update(add)
				
			}
		}
	}
}
